package com.wang.luntan.users.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wang.luntan.common.pojo.ApiResponse;
import com.wang.luntan.common.pojo.ApiResponseEnum;
import com.wang.luntan.common.pojo.JSONEnum;
import com.wang.luntan.common.service.service.BaseServiceImpl;
import com.wang.luntan.common.util.ConstatFinalUtil;
import com.wang.luntan.common.util.PageInfoUtil;
import com.wang.luntan.users.mapper.IAtAdminsDao;
import com.wang.luntan.users.mapper.IAtUsersDao;
import com.wang.luntan.users.pojo.AtAdmins;
import com.wang.luntan.users.pojo.AtUsers;
import com.wang.luntan.users.service.IUsersDbService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 用户的service
 *
 * @author Wangsh
 */
@Service("usersDbService")
@Log4j2
public class UsersDbServiceImpl extends BaseServiceImpl implements IUsersDbService {
    /**
     * dao如何赋值 ~木有写Dao的实现类,无法去顶@Repository(仓库) ~session.getMapper();
     */
    @Autowired
    private IAtAdminsDao adminsDao;
    @Autowired
    private IAtUsersDao usersDao;

    @Override
    public ApiResponse<Object> saveOneAdminsService(AtAdmins admins) {
        ApiResponse<Object> apiResponse = new ApiResponse<Object>();
        //添加管理员密码的时候,进行加密.
        admins.setPassword(this.encryptUtil.encodeStr(admins.getPassword()));
        /* 查询条件 */
        Map<String, Object> condMap = new HashMap<String, Object>();
        condMap.clear();
        condMap.put("email", admins.getEmail());
        ApiResponse<AtAdmins> apiRes = this.findOneAdminsService(condMap);
        /* 获取对象 */
        AtAdmins adminRes = apiRes.getDataOneJava();
        if (adminRes != null) {
            /* 用户名已经存在,请换一个 */
            apiResponse.setCode(ApiResponseEnum.INFO_EMAIL_EXISTS.getStatus());
            apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
            return apiResponse;
        }

        admins.setCreateTime(new Date());
        admins.setUpdateTime(new Date());
        admins.setLastLoginTime(new Date());
        admins.setPubTime(new Date());

        int res = this.adminsDao.save(admins);
        if (res > 0) {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put(JSONEnum.EFFECT.getName(), res);
            dataMap.put(JSONEnum.ID.getName(), admins.getId());
            apiResponse.setDataOne(dataMap);

            apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
        } else {
            apiResponse.setCode(ApiResponseEnum.STATUS_FAILED.getStatus());
        }
        apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
        return apiResponse;
    }

    @Override
    public ApiResponse<Object> updateOneAdminsService(AtAdmins admins) {
        ApiResponse<Object> apiResponse = new ApiResponse<Object>();
        /* 查询条件 */
        Map<String, Object> condMap = new HashMap<String, Object>();
        condMap.clear();
        condMap.put("email", admins.getEmail());
        ApiResponse<AtAdmins> apiRes = this.findOneAdminsService(condMap);
        /* 获取对象 */
        AtAdmins adminRes = apiRes.getDataOneJava();
        if (adminRes != null && adminRes.getId() != admins.getId()) {
            /* 用户名已经存在,请换一个 */
            apiResponse.setCode(ApiResponseEnum.INFO_EMAIL_EXISTS.getStatus());
            apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
            return apiResponse;
        }

        admins.setUpdateTime(new Date());
        int res = this.adminsDao.update(admins);
        if (res > 0) {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put(JSONEnum.EFFECT.getName(), res);
            dataMap.put(JSONEnum.ID.getName(), admins.getId());
            apiResponse.setDataOne(dataMap);

            apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
        } else {
            apiResponse.setCode(ApiResponseEnum.STATUS_FAILED.getStatus());
        }
        apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
        return apiResponse;
    }

    @Override
    public ApiResponse<Object> deleteOneAdminsService(Map<String, Object> condMap) {
        ApiResponse<Object> apiResponse = new ApiResponse<Object>();
        int res = this.adminsDao.delete(condMap);
        if (res > 0) {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put(JSONEnum.EFFECT.getName(), res);
            apiResponse.setDataOne(dataMap);

            apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
        } else {
            apiResponse.setCode(ApiResponseEnum.STATUS_FAILED.getStatus());
        }
        apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
        return apiResponse;
    }

    @Override
    public ApiResponse<AtAdmins> findOneAdminsService(Map<String, Object> condMap) {
        ApiResponse<AtAdmins> apiResponse = new ApiResponse<AtAdmins>();
        apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
        Map<String, AtAdmins> data = new HashMap<String, AtAdmins>();
        AtAdmins admins = this.adminsDao.findOne(condMap);
        /* 将结果放到JSON中 */
        data.put(ApiResponseEnum.NAME_ONE.getName(), admins);
        apiResponse.setDataOne(data);
        apiResponse.setDataOneJava(admins);
        apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
        return apiResponse;
    }


    @Override
    public ApiResponse<AtAdmins> findCondListAdminsService(PageInfoUtil pageInfoUtil, Map<String, Object> condMap) {
        ApiResponse<AtAdmins> apiResponse = new ApiResponse<AtAdmins>();
        apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
        List<AtAdmins> adminsList = Collections.EMPTY_LIST;

        Map<String, List<AtAdmins>> dataList = new HashMap<String, List<AtAdmins>>();
        /* 对关键字进行模糊匹配 */
        if (condMap.get("keyword") != null && !"".equalsIgnoreCase(condMap.get("keyword") + "")) {
            condMap.put("keyword", "%" + condMap.get("keyword") + "%");
        }

        /* 设置分页相关信息 */
        if (pageInfoUtil != null) {
            /* 设置分页信息 */
            Page<AtAdmins> page = PageHelper.startPage(pageInfoUtil.getCurrentPage(), pageInfoUtil.getPageSize());
            adminsList = this.adminsDao.findList(condMap);
            pageInfoUtil.setTotalRecord(Integer.valueOf(page.getTotal() + ""));
            /* 向接口中放分页信息 */
            apiResponse.setPageInfoUtil(pageInfoUtil);
        } else {
            adminsList = this.adminsDao.findList(condMap);
        }

        /* 将结果放到JSON中 */
        dataList.put(ApiResponseEnum.NAME_LIST.getName(), adminsList);
        apiResponse.setDataListJava(adminsList);
        apiResponse.setDataList(dataList);
        apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
        return apiResponse;
    }

    @Override
    public ApiResponse<Object> saveOneUsersService(AtUsers users) {
        ApiResponse<Object> apiResponse = new ApiResponse<Object>();
        Map<String, AtUsers> data = new HashMap<String, AtUsers>();
        /* 查询条件 */
        Map<String, Object> condMap = new HashMap<String, Object>();
        condMap.clear();
        condMap.put("email", users.getEmail());
        ApiResponse<AtUsers> apiRes = this.findOneUsersService(condMap);
        /* 获取对象 */
        AtUsers userRes = apiRes.getDataOneJava();
        if (userRes != null) {
            /* 用户名已经存在,请换一个 */
            apiResponse.setCode(ApiResponseEnum.INFO_EMAIL_EXISTS.getStatus());
            apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
            return apiResponse;
        }
        int res = this.usersDao.save(users);
        if (res > 0) {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put(JSONEnum.EFFECT.getName(), res);
            dataMap.put(JSONEnum.ID.getName(), users.getId());
            data.put(ApiResponseEnum.NAME_ONE.getName(), users);
            apiResponse.setDataOne(dataMap);

            apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());

        } else {
            apiResponse.setCode(ApiResponseEnum.STATUS_FAILED.getStatus());
        }
        apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
        return apiResponse;
    }

    @Override
    public ApiResponse<Object> updateOneUsersService(AtUsers users) {
        ApiResponse<Object> apiResponse = new ApiResponse<Object>();
        /* 查询条件 */
        Map<String, Object> condMap = new HashMap<String, Object>();
        condMap.clear();
        condMap.put("email", users.getEmail());
        ApiResponse<AtUsers> apiRes = this.findOneUsersService(condMap);
        /* 获取对象 */
        AtUsers userRes = apiRes.getDataOneJava();
        if (userRes != null && userRes.getId() != users.getId()) {
            /* 用户名已经存在,请换一个 */
            apiResponse.setCode(ApiResponseEnum.INFO_EMAIL_EXISTS.getStatus());
            apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
            return apiResponse;
        }

        int res = this.usersDao.update(users);
        if (res > 0) {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put(JSONEnum.EFFECT.getName(), res);
            dataMap.put(JSONEnum.ID.getName(), users.getId());
            dataMap.put(ApiResponseEnum.NAME_ONE.getName(), users);

            apiResponse.setDataOne(dataMap);

            apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());

        } else {
            apiResponse.setCode(ApiResponseEnum.STATUS_FAILED.getStatus());
        }
        apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
        return apiResponse;
    }

    @Override
    public ApiResponse<Object> updateOneUsersService(AtUsers users, Map<String, Object> paramsMap) {
        /* 先更新用户的信息 */
        ApiResponse<Object> apiResponse = new ApiResponse<Object>();
        try {
            String fileName = paramsMap.get("fileName") + "";
            InputStream is = (InputStream) paramsMap.get("inputStream");

            /* 上传文件的相对路径   /uploadfile/  */
            String uploadFile = ConstatFinalUtil.CONFIG_JSON.getString("website.uploadFile");
            /* 存储的是网址的绝对路径 */
            String souPath = users.getPhotoPath();
            /* 真实路径  D:/项目空间/usersCenter/usersCenter-web/usersCenter-web-head/src/main/webapp/ */
            String truePath = ConstatFinalUtil.CONFIG_JSON.getString("website.truePath");
            /* 网站的相对路径 */
            String tarRelaPath = uploadFile + "users/" + this.dateFormatUtil.dateStr(new Date()) + "/" + UUID.randomUUID().toString() +
                    fileName.substring(fileName.lastIndexOf("."), fileName.length());
            File tarTrueFile = new File(truePath + tarRelaPath.substring(1));

            /* 创建父目录 */
            if (!tarTrueFile.getParentFile().exists()) {
                tarTrueFile.getParentFile().mkdirs();
            }
            users.setPhotoPath(tarRelaPath);
            FileOutputStream fos = new FileOutputStream(tarTrueFile);
            /* 复制文件 */
            boolean flag = this.fileUtil.copyFile(is, fos);
            if (flag) {
                if (souPath != null && !"".equalsIgnoreCase(souPath)) {
                    souPath = truePath + souPath.substring(1);
                    /* 相对路径 */
                    File souFile = new File(souPath);
                    if (!souFile.delete()) {
                        log.error("删除原始文件失败:原始文件路径:{}", souFile.getAbsolutePath());
                    }
                }
            }

            apiResponse = this.updateOneUsersService(users);
        } catch (Exception e) {
            log.error("上传头像失败了,email:{}", users.getEmail(), e);
        }
        return apiResponse;
    }

    @Override
    public ApiResponse<Object> deleteOneUsersService(Map<String, Object> condMap) {
        ApiResponse<Object> apiResponse = new ApiResponse<Object>();
        int res = this.usersDao.delete(condMap);
        if (res > 0) {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put(JSONEnum.EFFECT.getName(), res);
            apiResponse.setDataOne(dataMap);

            apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
        } else {
            apiResponse.setCode(ApiResponseEnum.STATUS_FAILED.getStatus());
        }
        apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
        return apiResponse;
    }

    @Override
    public ApiResponse<AtUsers> findOneUsersService(Map<String, Object> condMap) {
        ApiResponse<AtUsers> apiResponse = new ApiResponse<AtUsers>();
        apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
        Map<String, AtUsers> data = new HashMap<String, AtUsers>();
        AtUsers users = this.usersDao.findOne(condMap);

        data.put(ApiResponseEnum.NAME_ONE.getName(), users);
        /* 将结果放到JSON中 */
        apiResponse.setDataOne(data);
        apiResponse.setDataOneJava(users);
        apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
        return apiResponse;
    }

    @Override
    public ApiResponse<AtUsers> findCondListUsersService(PageInfoUtil pageInfoUtil, Map<String, Object> condMap) {
        ApiResponse<AtUsers> apiResponse = new ApiResponse<AtUsers>();
        apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
        List<AtUsers> usersList = Collections.EMPTY_LIST;

        Map<String, List<AtUsers>> dataList = new HashMap<String, List<AtUsers>>();
        /* 对关键字进行模糊匹配 */
        if (condMap.get("keyword") != null && !"".equalsIgnoreCase(condMap.get("keyword") + "")) {
            condMap.put("keyword", "%" + condMap.get("keyword") + "%");
        }

        /* 设置分页相关信息 */
        if (pageInfoUtil != null) {
            /* 设置分页信息 */
            Page page = PageHelper.startPage(pageInfoUtil.getCurrentPage(), pageInfoUtil.getPageSize());
            usersList = this.usersDao.findList(condMap);
            pageInfoUtil.setTotalRecord(Integer.valueOf(page.getTotal() + ""));
            /* 向接口中放分页信息 */
            apiResponse.setPageInfoUtil(pageInfoUtil);
        } else {
            usersList = this.usersDao.findList(condMap);
        }
        /* 将结果放到JSON中 */
        dataList.put(ApiResponseEnum.NAME_LIST.getName(), usersList);
        apiResponse.setDataListJava(usersList);
        apiResponse.setDataList(dataList);
        apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
        return apiResponse;
    }

    /**
     * 重置密码->查询当前登录用户
     */
    @Override
    public AtAdmins findOneByName(String str) {
        return adminsDao.findOneByName(str);
    }

    /**
     * 重置密码->比较用户
     */
    @Override
    public JSONObject updateOneAdmins(AtAdmins admins) {

        JSONObject resultJson = new JSONObject();
        /* 保存 */
        int res = this.adminsDao.update(admins);

        if (res > 0) {
            JSONObject dataJson = new JSONObject();
            dataJson.put("effect", res);
            dataJson.put("id", admins.getId());

            resultJson.put("data", dataJson);
            /* 成功 */
            resultJson.put("code", "0");
            resultJson.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
        } else {
            /* 失败 */
            resultJson.put("code", "1");
            resultJson.put("info", ConstatFinalUtil.INFO_JSON.get("1"));
        }
        return resultJson;
    }
}
